/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月10日 下午12:10:14
 */

package datang.dtdb.executor.resultset;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import datang.dtdb.exceptions.ResultSetException;
import datang.dtdb.exceptions.TypeException;
import datang.dtdb.mapping.MappedStatement;
import datang.dtdb.mapping.ResultMap;

/**
 * 处理返回值
 */
public class DefaultResultSetHandler implements ResultSetHandler {

	@Override
	public List<Object> handleResultSets(MappedStatement mappendStatement, Statement statement) {
		ArrayList<Object> resultObjects = new ArrayList<>();
		ResultSet resultSet = null;
		try {
			resultSet = statement.getResultSet();
			List<ResultMap> resultMaps = mappendStatement.getresultMaps();
			for (ResultMap resultMap : resultMaps) {
				Class<?> resultType = resultMap.getResultType();
				Field[] fields = resultType.getDeclaredFields();
				while (resultSet.next()) {
					Object resultObject = resultType.newInstance();
					for (int i = 0; i < fields.length; i++) {
						Field field = fields[i];
						field.setAccessible(true);
						field.set(resultObject, resultSet.getObject(field.getName()));
					}
					resultObjects.add(resultObject);
				}
			}

		} catch (Exception e) {
			throw new ResultSetException("结果集映射错误", e);
		} finally {
			closeResultSet(resultSet);
		}

		return resultObjects;
	}

	/**
	 * 关闭ResultSet
	 * */
	private void closeResultSet(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			throw new ResultSetException("关闭ResultSet错误", e);
		}
	}
}
